package cn.zsb.web;

import cn.zsb.entity.Advtise;
import cn.zsb.entity.Page;
import cn.zsb.entity.Result;
import cn.zsb.service.AdvtiseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author oldliu
 * @since 1.0
 */
@RestController
@RequestMapping("adv")
@Validated
@Api("广告管理")
@CrossOrigin(origins = "*", allowedHeaders = {"Authorization", "Content-Type"})
public class AdvtiseController {
    @Value("${upload.imgpath}")
    private String path;
    @Autowired
    private AdvtiseService advtiseService;
    //页码大于等于1
    //pagesize>=1
    @ApiOperation("广告搜索")
    @GetMapping("search")
    public Page<Advtise> advtiseAjax(@ApiParam(name = "title",value = "广告标题搜索") @RequestParam(required = false) String title,
                                     @ApiParam(name = "page",value = "页码")@Range(min = 1,message = "页码太小了") @RequestParam(name = "page", defaultValue = "1") int pageNo,
                                     @ApiParam(name = "limit",value = "页大小，最小是3，最多100") @Range(min = 3,max = 100,message = "页大小不合适") @RequestParam(name = "limit", defaultValue = "10") int pageSize,
                                     @ApiParam(name = "start",value = "广告发布时间的搜索条件的起始值")@DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(name = "start", required =
                                             false) Date start,
                                     @ApiParam(name = "end",value = "广告发布时间的搜索条件的结束值")@DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(name = "end", required =
                                             false) Date end
    ) {
//        if(Math.random()>0.5)
//            throw  new RuntimeException("erro11111");
//
        Page<Advtise> p = advtiseService.page(title, start, end, pageNo, pageSize);
        return p;
    }

    @PostMapping("add")
    public Result add(Advtise adv, @RequestParam(name = "a_imgurl", required = false) MultipartFile file) {
        if (!file.isEmpty()) {
            File f = new File(path);
            if (!f.exists())
                f.mkdir();
            //原来的文件名
            String filename = file.getOriginalFilename();
            String houzhui = filename.substring(filename.lastIndexOf('.'));
            String newName = UUID.randomUUID() + houzhui;
            adv.setImgurl(newName);
            try {
                file.transferTo(new File(f, newName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        int add = advtiseService.add(adv);
        return Result.success();
    }

    @ApiOperation("文件上传，返回图片的地址")
    @PostMapping("upload")
    public Result upload(@RequestParam MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return Result.error("没有选择文件");
        }
        File f = new File(path);
        if (!f.exists())
            f.mkdir();
        //原来的文件名
        String filename = file.getOriginalFilename();
        String houzhui = filename.substring(filename.lastIndexOf('.'));
        String newName = UUID.randomUUID() + houzhui;

        try {
            file.transferTo(new File(f, newName));

            return Result.success(newName, "上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("上传失败：" + e);
        }
    }

    @ApiOperation("广告新增")
    @PostMapping("insert")
    public Result add2(@Valid @RequestBody Advtise adv) {
//        if(StringUtils.isEmpty(adv.getTitle())){
//            return Result.error("标题居然没有？！");
//        }
       int add = advtiseService.add(adv);
        return Result.success();
    }

    @ApiOperation("查看单个广告的信息")
    @GetMapping("get/{id}")
    // @ApiImplicitParam(name = "有个地址栏的restful风格的id")
    public Result toAdd(@ApiParam("编号") @PathVariable long id) {
        Advtise ad = this.advtiseService.get(id);

        return ad==null ? Result.error("么有找到"):Result.success(ad);
    }
}
